package com.example.ercmssystem2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);

    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        logger.info("配置 SecurityFilterChain");
        
        http
            .csrf(csrf -> csrf.disable())
            .cors(cors -> cors.disable())
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers(
                    new AntPathRequestMatcher("/"),
                    new AntPathRequestMatcher("/css/**"),
                    new AntPathRequestMatcher("/js/**"),
                    new AntPathRequestMatcher("/images/**"),
                    new AntPathRequestMatcher("/lib/**"),
                    new AntPathRequestMatcher("/webjars/**"),
                    new AntPathRequestMatcher("/login"),
                    new AntPathRequestMatcher("/dashboard"),
                    new AntPathRequestMatcher("/department"),
                    new AntPathRequestMatcher("/dispatch"),
                    new AntPathRequestMatcher("/dispatch/event/**"),
                    new AntPathRequestMatcher("/dispatch/**"),
                    new AntPathRequestMatcher("/events"),
                    new AntPathRequestMatcher("/resource"),
                    new AntPathRequestMatcher("/statistics"),
                    new AntPathRequestMatcher("/user"),
                    new AntPathRequestMatcher("/terminal"),
                    new AntPathRequestMatcher("/profile"),
                    new AntPathRequestMatcher("/error"),
                    new AntPathRequestMatcher("/auth/status"),
                    new AntPathRequestMatcher("/task-report"),
                    new AntPathRequestMatcher("/task-report/**"),
                    new AntPathRequestMatcher("/api/completion/**"),
                    new AntPathRequestMatcher("/api/auth/login"),
                    new AntPathRequestMatcher("/api/auth/register"),
                    new AntPathRequestMatcher("/api/auth/verify"),
                    new AntPathRequestMatcher("/api/auth/logout"),
                    new AntPathRequestMatcher("/api/auth/refresh"),
                    new AntPathRequestMatcher("/api/dashboard/stats"),
                    new AntPathRequestMatcher("/api/events/recent"),
                    new AntPathRequestMatcher("/api/departments/**"),
                    new AntPathRequestMatcher("/api/users"),
                    new AntPathRequestMatcher("/api/health"),
                    new AntPathRequestMatcher("/api/info"),
                    new AntPathRequestMatcher("/v3/api-docs/**"),
                    new AntPathRequestMatcher("/swagger-ui/**"),
                    new AntPathRequestMatcher("/swagger-ui.html"),
                    new AntPathRequestMatcher("/swagger-resources/**"),
                    new AntPathRequestMatcher("/webjars/**")
                ).permitAll()
                .requestMatchers(new AntPathRequestMatcher("/system/**")).hasRole("SYSTEM_ADMIN")
                .requestMatchers(new AntPathRequestMatcher("/dept/**")).hasRole("DEPT_ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/dashboard", true)
                .failureUrl("/login?error=true")
                .permitAll()
            )
            .logout(logout -> logout
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout")
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .permitAll()
            )
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
    
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        logger.info("创建 AuthenticationManager");
        return authConfig.getAuthenticationManager();
    }
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        logger.info("配置 AuthenticationManagerBuilder，使用 UserDetailsService 和 PasswordEncoder");
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }
} 